<?php

/**
 *  会员登陆模型，处理登录相关信息
 * --------------------------------------------------------
 * @copyright http://lin.97md.net
 * @access       MyDream
 * @author      zxing@97md.net
 * $Id: login.model.php 64 2012-02-02 06:50:45Z thesmilelin@gmail.com $
 * $Date: 2012-02-02 06:50:45 +0000 (Thu, 02 Feb 2012) $
 * --------------------------------------------------------
 * @example
 */
// 登录
function login($username, $password) {
    $u_id = 0;
    // 查询当前用户名 是否存在
    $sql = "SELECT * FROM `users` WHERE `login_name`='" . $username . "' AND `password`='" . password($password) . "' LIMIT 1;";
    //$sql = 'SELECT * FROM `users` WHERE `login_name`=' . $username . ' AND `password`=' . password( $password ) . ' LIMIT 1 ';
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $rows = mysql_fetch_assoc($result);
        $u_id = $rows["id"];
        if (!empty($u_id)) {
            // 更新当前用户登录信息
            $sql = 'UPDATE `users` SET `last_time`=' . time() . ' , `last_ip`=\'' . getIp() . '\' ,`login_times`=`login_times`+1 WHERE `id`=' . $u_id . ' LIMIT 1 ;';
            $result = mysql_query($sql);
            // 写入SESSION
            if (!isset($_SESSION)) {
                session_start();
            }
            foreach ($rows as $key => $value) {
                $_SESSION[$key] = $value;
            }
        }
    }
   
    return $u_id;
}

// 检查当前用户是否登录状态
function is_login() {
    if (!isset($_SESSION)) {
        session_start();
    }
    return empty($_SESSION['id']) ? false : $_SESSION['id'];
}

// 退出
function logout() {
    if (!isset($_SESSION)) {
        session_start();
    }
    $_SESSION = array();
    //彻底销毁session
    session_destroy();
}